package com.gree.scmservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gree.common.entity.ReturnVo;
import com.gree.common.entity.SysApiRoleVo;
import com.gree.framework.entity.CusUserDetails;
import com.gree.framework.entity.SysUser;
import com.gree.framework.utils.SecurityUtils;
import com.gree.scmservice.dao.ApiRoleDao;
import com.gree.scmservice.service.GscmSysRoleApiService;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.entity.Record;
import org.nutz.dao.pager.Pager;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class GscmSysRoleApiServiceImpl implements GscmSysRoleApiService {

    @Autowired
    private ApiRoleDao apiRoleDao;

    @Autowired
    private Dao dao;

    @Autowired
    DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    TransactionDefinition transactionDefinition;


    @PostConstruct
    public void init()
    {
        /*List<SysApiRoleVo> sysApiRoleVos = dao.query(SysApiRoleVo.class,null);
        SpringxUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(""), sysApiRoleVos);*/
    }

    @Override
    public NutMap displaySysApiRole(JSONObject jsonObject) {
        CusUserDetails cusUserDetails = SecurityUtils.getUser();
        SysUser sysUser = cusUserDetails.getUser();
        String comp = sysUser.getComp();
        String filter = "where 1 = 1";
        if(!"".equals(jsonObject.getString("dsca")) && jsonObject.getString("dsca")!=null){
            filter+=" and api.dsca like '%"+jsonObject.getString("dsca")+"%'";
        }
        if(!"".equals(jsonObject.getString("apiurl")) && jsonObject.getString("apiurl")!=null){
            filter+=" and api.apiurl like '%"+jsonObject.getString("apiurl")+"%'";
        }
        if(!"".equals(jsonObject.getString("method")) && jsonObject.getString("method")!=null){
            filter+=" and api.method = '"+jsonObject.getString("method")+"'";
        }
        if(!"".equals(jsonObject.getString("type")) && jsonObject.getString("type")!=null){
            filter+=" and api.type = '"+jsonObject.getString("type")+"'";
        }
        filter+=" order by api.createtime desc";
        int count = apiRoleDao.getApiRoleCount(comp,filter);
        Pager pager = dao.createPager(jsonObject.getIntValue("page"),jsonObject.getIntValue("pagesize"));
        List<Record> dataList = apiRoleDao.displayApiRole(comp,filter,count,pager);
        for(Record record:dataList){
            List<Record> list = querySysApiUser(record.getLong("id"));
            ArrayList<String> usernames = new ArrayList<>();
            for(Record re: list){
                usernames.add(re.getString("username"));
            }
            record.set("users",usernames);
        }
        return NutMap.NEW().addv("dataList",dataList).addv("page",pager);
    }

    @Override
    public ReturnVo insertSysApiRole(SysApiRoleVo sysApiRoleVo) {
        List<SysApiRoleVo> sysApiRoleVos = new ArrayList<SysApiRoleVo>();
        sysApiRoleVo.setCreatetime(new Date());
        sysApiRoleVos.add(sysApiRoleVo);
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        try{
            List<SysApiRoleVo> sysApiRoleVoList = apiRoleDao.insertApiRole(sysApiRoleVos);
            String[] users = sysApiRoleVo.getUsers();
            if(sysApiRoleVoList.size() == 0){
                dataSourceTransactionManager.rollback(transactionStatus);
                return new ReturnVo("500","error");
            }
            sysApiRoleVo = sysApiRoleVoList.get(0);
            if(users!=null){
                for(String username : users){
                    insertSysApiUser(sysApiRoleVo.getId(),username);
                }
            }
            dataSourceTransactionManager.commit(transactionStatus);
            return new ReturnVo("200","success");
        }catch (Exception e) {
            dataSourceTransactionManager.rollback(transactionStatus);
            return new ReturnVo("500", "fail");
        }

    }

    @Override
    public ReturnVo updateSysApiRole(SysApiRoleVo sysApiRoleVo) {
        List<SysApiRoleVo> sysApiRoleVos = new ArrayList<SysApiRoleVo>();
        sysApiRoleVos.add(sysApiRoleVo);
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        try{
            int result = apiRoleDao.updateApiRole(sysApiRoleVos);
            deleteSysApiUserByApiIDs(new Long[]{sysApiRoleVo.getId()});
            String[] users = sysApiRoleVo.getUsers();
            if(users!=null){
                for(String username : users){
                    insertSysApiUser(sysApiRoleVo.getId(),username);
                }
            }
            dataSourceTransactionManager.commit(transactionStatus);
            return new ReturnVo("200","success");
        }catch (Exception e) {
            dataSourceTransactionManager.rollback(transactionStatus);
            return new ReturnVo("500", "fail");
        }
    }

    @Override
    public ReturnVo deleteApiRoleByIds(Long[] infoIds) {
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        try{
            deleteSysApiUserByApiIDs(infoIds);
            apiRoleDao.deleteApiRoleByIds(infoIds);
            dataSourceTransactionManager.commit(transactionStatus);
            return new ReturnVo("200","success");
        }catch (Exception e) {
            dataSourceTransactionManager.rollback(transactionStatus);
            return new ReturnVo("500", "fail");
        }
    }

    @Override
    public List querySysApiUser(Long apiId) {
        List<Record> list = dao.query("SYS_API_USER", Cnd.where("api_id","=", apiId));
        return list;
    }

    @Override
    public void insertSysApiUser(Long apiId,String username) {
        dao.insert("SYS_API_USER", Chain.make("api_id",apiId).add("username",username));
    }

    @Override
    public int deleteSysApiUser(Long apiId, String username) {
        return dao.clear("SYS_API_USER", Cnd.where("api_id","=", apiId).and("username","=",username));
    }

    @Override
    public int deleteSysApiUserByApiIDs(Long[] apiIds) {
        return dao.clear("SYS_API_USER", Cnd.where("api_id","in", apiIds));
    }
}
